/**
 * 
 */
package com.opengroupe.dao.impl;

import java.util.List;

import javax.ejb.Stateless;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.opengroupe.dao.AccessCodeDao;
import com.opengroupe.entities.AccessCode;

/**
 * Home object for domain model class Candidat.
 * 
 * @see com.opengroupe.entities.Candidat
 * @author MMB11447
 */
@Stateless
public class AccessCodeDaoImpl extends JpaDaoSupport implements AccessCodeDao {

	private static final Log log = LogFactory.getLog(AccessCodeDaoImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opengroupe.dao.Dao#persist(java.lang.Object)
	 */
	@Override
	public AccessCode persist(AccessCode object) {
		log.debug("persisting AccessCode instance");
		try {
			getJpaTemplate().persist(object);
			log.debug("persist successful");
			return object;
		} catch (DataAccessException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opengroupe.dao.Dao#remove(java.lang.Object)
	 */
	@Override
	public void remove(AccessCode object) {
		log.debug("removing AccessCode instance");
		try {
			getJpaTemplate().remove(object);
			log.debug("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opengroupe.dao.Dao#merge(java.lang.Object)
	 */
	@Override
	public AccessCode merge(AccessCode object) {
		log.debug("merging AccessCode instance");
		try {
			AccessCode result = getJpaTemplate().merge(object);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opengroupe.dao.Dao#findById(java.lang.Integer)
	 */
	@Override
	public AccessCode findById(Integer id) {
		return null;
	}

	@Override
	public AccessCode findById(String id) {
		log.debug("getting AccessCode instance with id: " + id);
		try {
			AccessCode instance = getJpaTemplate().find(AccessCode.class, id);
			log.debug("get successful");
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public AccessCode lastGeneratedCode() {
		String query = "select ac from AccessCode ac order by ac.generationDate DESC limit(1)";
		List<AccessCode> res = getJpaTemplate().find(query);

		if (res != null && res.size() > 0) {
			return res.get(0);
		} else {
			return null;
		}
	}

}
